package com.fullstack.landscape.editor.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * @author leven.chen
 * @project landscape-editor
 * @date 2019/4/10 9:55
 * @apiNote
 */
@Component
public class AttachmentService {

    /**
     * logger
     */
    private static final Logger log = getLogger(AttachmentService.class);


    private final ConfigService configService;

    private static final String IMAGE_DIR = "/attachment";
    private static final String VIDEO_DIR = "/attachment";


    private static final List<String> IMAGE_EXTENSION_LIST = Lists.newArrayList("png", "jpeg", "jpg");

    private static final List<String> VIDEO_EXTENSION_LIST = Lists.newArrayList("mp4");

    public AttachmentService(ConfigService configService) {
        this.configService = configService;
    }

    public String save(MultipartFile file) {
        String contentType = file.getContentType();
        String name = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(name);

        try {
            String storeDir = this.getStoreDir(extension);
            Path path = Paths.get(storeDir);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }

            InputStream inputStream = file.getInputStream();
            String fileNameId = IdUtil.simpleUUID();
            String newFileName = fileNameId + "." + extension;
            String filePath = storeDir + File.separator + newFileName;

            OutputStream out = new FileOutputStream(filePath);
            IOUtils.copy(inputStream, out);
            return newFileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("文件保存失败，请检查后再试");
    }

    public String save(String fileName, File file) {
        String extension = FilenameUtils.getExtension(fileName);

        try {
            String storeDir = this.getStoreDir(extension);
            Path path = Paths.get(storeDir);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }

            InputStream inputStream = new FileInputStream(file);
            String fileNameId = IdUtil.simpleUUID();
            String newFileName = fileNameId + "." + extension;
            String filePath = storeDir + File.separator + newFileName;

            OutputStream out = new FileOutputStream(filePath);
            IOUtils.copy(inputStream, out);
            return newFileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("文件保存失败，请检查后再试");
    }

    /**
     * 保存图片文件
     *
     * @return 保存路径
     */
    private String getStoreDir(String extension) {

        if (StringUtils.isBlank(extension)) {
            throw new RuntimeException("不支持的文件类型");
        }

        String workspace = configService.getWorkspace();
        String imagePath = workspace + IMAGE_DIR;
        String videoPath = workspace + VIDEO_DIR;
        if (CollectionUtil.contains(IMAGE_EXTENSION_LIST, extension.trim().toLowerCase())) {
            return imagePath;
        }

        if (CollectionUtil.contains(VIDEO_EXTENSION_LIST, extension.trim().toLowerCase())) {
            return videoPath;
        }

        throw new RuntimeException("不支持的文件类型");
    }


    public String getStoreDir() {
        String workspace = configService.getWorkspace();
        return workspace + IMAGE_DIR;
    }


    public String getWorkspace() {
        return configService.getWorkspace();
    }


    public void removeAttachment(String videoPath) {
        if (StringUtils.isBlank(videoPath)) {
            return;
        }

        String storeDir = this.getStoreDir() + File.separator + videoPath;
        try {
            FileUtils.forceDelete(new File(storeDir));
        } catch (NoSuchFileException | FileNotFoundException e) {
            log.warn("附件信息不存在{}", e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("删除异常，请刷新后再试");
        }
    }
}
